<template>
  <div class="container dark-theme" @click="closeMenuOnClickOutside">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="logo">“沈誉通”信用生活综合系统</div>
      <div class="nav">
        <!-- <router-link to="/home">首页</router-link> -->
        <router-link to="/credit-life">信用生活</router-link>
        <router-link to="/credit-business">信用商业</router-link>
        <router-link to="/behavior">亲社会行为</router-link>
        <router-link to="/news">新闻资讯</router-link>
        <router-link to="/credit-management">信用管理</router-link>
      </div>
      <div class="user-menu" ref="userMenu">
        <div class="avatar-box">
          <img
            :src="user.icon || defaultIcon"
            class="avatar"
            alt="用户头像"
            @click.stop="toggleMenu"
            @error="handleImageError"
          />
        </div>
        <div v-if="isMenuOpen" class="dropdown-menu">
          <div class="menu-item" @click="goToProfile">个人信息</div>
          <div class="menu-item" @click="logout">退出登录</div>
        </div>
      </div>
    </div>

    <div class="screen">
      <div class="right-section">
        <div v-if="!news.id" class="loading">加载中...</div>
        <div v-else>
          <div class="header-detail">
            <div class="header-back-btn" @click="goBack"><i class="el-icon-arrow-left"></i></div>
            <div class="header-title">新闻详情</div>
            <div class="header-share">...</div>
          </div>
          <div class="news-info-box" ref="swiper" @touchstart="moveStart" @touchmove="moving" @touchend="moveEnd">
            <div class="swiper-wrapper" :style="{ transform: `translateX(-${active * 100}%)` }">
              <div class="swiper-item" v-for="(img, i) in news.images" :key="i">
                <img :src="img" alt="新闻图片" @error="handleImageError" />
              </div>
            </div>
            <div class="swiper-dots" v-if="news.images.length > 1">
              <span
                v-for="(img, i) in news.images"
                :key="i"
                class="dot"
                :class="{ active: i === active }"
                @click="go(i)"
              ></span>
            </div>
          </div>
          <div class="basic">
            <div class="basic-icon" @click="toOtherInfo">
              <img :src="news.icon || defaultIcon" alt="用户头像" @error="handleImageError" />
            </div>
            <div class="basic-info">
              <div class="name">{{ news.name || '未知用户' }}</div>
              <span class="time">{{ formatTime(news.createTime) }}</span>
            </div>
            <div class="follow-btn-container">
              <div
                class="logout-btn"
                @click="follow"
                v-show="user.id && user.id !== news.userId"
              >
                {{ followed ? '取消关注' : '关注' }}
              </div>
            </div>
          </div>
          <div class="news-divider"></div>
          <div class="news-text" v-html="news.content || '暂无内容'"></div>
          <div class="news-divider"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import Vue from 'vue';

axios.interceptors.request.use(
  (config) => {
    const token = window.sessionStorage.getItem('token') || localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

export default {
  name: 'NewsDetail',
  data() {
    return {
      news: { images: [], icon: '', content: '', userId: null, createTime: '' },
      user: { id: null, icon: '' },
      followed: false,
      isMenuOpen: false,
      imageBaseUrl: 'http://localhost:8089',
      active: 0,
      start: { x: 0, y: 0 },
      move: { x: 0, y: 0 },
      sensitivity: 60,
      duration: 300,
      isMoving: false,
      defaultIcon: '',          // TODO 默认头像
    };
  },
  created() {
    const id = this.$route.params.id;
    this.queryNewsById(id);
    this.queryUser();
  },
  methods: {
    formatImageUrl(imagePath) {
      if (!imagePath) return this.defaultIcon;
      if (imagePath.startsWith('http')) return imagePath;
      return `${this.imageBaseUrl}${imagePath}`;
    },
    async queryNewsById(id) {
      try {
        const { data } = await axios.get(`/news/news/news-detail/${id}`, {
          params: { userId: this.user.id || localStorage.getItem('userId') },
        });
        if (data && data.success && data.data) {
          data.data.images = data.data.images
            ? data.data.images.split(',').map(img => this.formatImageUrl(img.trim()))
            : [];
          data.data.icon = this.formatImageUrl(data.data.icon);
          this.news = data.data;
          if (this.user.id && this.user.id !== data.data.userId) {
            await this.isFollowed();
          }
        } else {
          this.$message.error(data.msg || '获取新闻详情失败');
        }
      } catch (err) {
        this.$message.error(err.response?.data?.msg || err.message || '获取新闻详情失败');
      }
    },
    async isFollowed() {
      try {
        const { data } = await axios.get(`/news/follow/or/not/${this.news.userId}`, {
          params: { userId: this.user.id || localStorage.getItem('userId') },
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
        });
        if (data && data.success) {
          this.followed = data.data;
        } else {
          this.$message.error(data.msg || '获取关注状态失败');
        }
      } catch (err) {
        this.$message.error(err.response?.data?.msg || err.message || '获取关注状态失败');
      }
    },
    async follow() {
      try {
        const response = await axios.post(
          `/news/follow/${this.news.userId}/${!this.followed}?userId=${this.user.id || localStorage.getItem('userId')}`,
          null,
          { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }
        );
        if (response.data && response.data.success) {
          this.$message.success(this.followed ? '已取消关注' : '已关注');
          this.followed = !this.followed;
        } else {
          this.$message.error(response.data.msg || '关注操作失败');
        }
      } catch (err) {
        this.$message.error(err.response?.data?.msg || err.message || '关注操作失败');
      }
    },
    async queryUser() {
      try {
        const { data } = await axios.get('/users/user/me', {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
        });
        if (data.success && data.data) {
          this.user = {
            ...data.data,
            icon: this.formatImageUrl(data.data.icon),
            id: data.data.id || localStorage.getItem('userId'),
          };
          localStorage.setItem('userId', this.user.id);
          this.queryUserInfo();
        }
      } catch (err) {
        this.$message.error(err.response?.data?.msg || err.message || '获取用户信息失败');
      }
    },
    queryUserInfo() {
      axios
        .get(`/users/user/basic`, {
          params: { userId: this.user.id || localStorage.getItem('userId') },
        })
        .then(({ data }) => {
          this.info = data || { introduce: '' };
          sessionStorage.setItem('userInfo', JSON.stringify(data));
        })
        .catch(err => this.$message.error(err.message));
    },
    formatTime(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
    },
    goBack() {
      this.$router.go(-1);
    },
    toOtherInfo() {
      if (this.news.userId === this.user.id) {
        this.$router.push('/user-information');
      } else {
        this.$router.push(`/other-info/${this.news.userId}`);
      }
    },
    handleImageError(event) {
      event.target.src = this.defaultIcon;
    },
    moveStart(e) {
      this.start.x = e.changedTouches[0].pageX;
      this.start.y = e.changedTouches[0].pageY;
    },
    moving(e) {
      e.preventDefault();
      let distanceX = e.changedTouches[0].pageX - this.start.x;
      let distanceY = e.changedTouches[0].pageY - this.start.y;
      if (Math.abs(distanceX) > Math.abs(distanceY)) {
        this.isMoving = true;
      }
    },
    moveEnd(e) {
      if (!this.isMoving) return;
      e.preventDefault();
      let distance = e.changedTouches[0].pageX - this.start.x;
      if (Math.abs(distance) > this.sensitivity) {
        if (distance < 0 && this.active < this.news.images.length - 1) {
          this.next();
        } else if (distance > 0 && this.active > 0) {
          this.prev();
        }
      }
      this.isMoving = false;
    },
    next() {
      if (this.active < this.news.images.length - 1) {
        this.active++;
      }
    },
    prev() {
      if (this.active > 0) {
        this.active--;
      }
    },
    go(index) {
      if (index >= 0 && index < this.news.images.length) {
        this.active = index;
      }
    },
    toggleMenu() {
      this.isMenuOpen = !this.isMenuOpen;
    },
    closeMenuOnClickOutside(event) {
      const menu = this.$refs.userMenu;
      if (menu && !menu.contains(event.target)) {
        this.isMenuOpen = false;
      }
    },
    goToProfile() {
      this.$router.push('/user-information');
      this.isMenuOpen = false;
    },
    async logout() {
      try {
        await axios.post('/users/user/logout');
        sessionStorage.removeItem('token');
        localStorage.removeItem('userId');
        window.location.href = '/';
      } catch (err) {
        this.$message.error(err.response?.data?.msg || err.message || '退出登录失败');
      }
    },
  },
};
</script>

<style scoped>
.container.dark-theme {
  background: radial-gradient(ellipse at center, #001e3c 0%, #000 100%);
  min-height: 100vh;
  color: #e0e0e0;
  font-family: 'Microsoft YaHei', sans-serif;
}
.header {
  display: flex;
  justify-content: space-between;
  padding: 10px 30px;
  background: #002d52;
  align-items: center;
}
.header .logo {
  font-size: 20px;
  color: #4fc3f7;
}
.header .nav a {
  margin: 0 10px;
  color: #e0e0e0;
  text-decoration: none;
}
.user-menu {
  position: relative;
}
.avatar-box img.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid #4fc3f7;
  object-fit: cover;
  cursor: pointer;
}
.dropdown-menu {
  position: absolute;
  top: 50px;
  right: 0;
  background: #002d52;
  border: 1px solid #4fc3f7;
  border-radius: 4px;
  z-index: 10;
}
.menu-item {
  padding: 10px;
  color: #e0e0e0;
  cursor: pointer;
}
.menu-item:hover {
  background: #014b75;
}
.screen {
  padding: 20px;
}
.right-section {
  flex: 1;
  max-width: 800px;
  margin: 0 auto;
}
.loading {
  text-align: center;
  font-size: 16px;
  color: #4fc3f7;
  padding: 20px;
}
.header-detail {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  background: #003b64;
  border-radius: 8px;
  margin-bottom: 20px;
}
.header-back-btn {
  font-size: 20px;
  cursor: pointer;
  color: #4fc3f7;
}
.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #e0e0e0;
}
.header-share {
  font-size: 20px;
  cursor: pointer;
  color: #4fc3f7;
}
.news-info-box {
  overflow: hidden;
  position: relative;
  border-radius: 8px;
  margin-bottom: 20px;
  aspect-ratio: 16/9;
}
.swiper-wrapper {
  display: flex;
  width: 100%;
  height: 100%;
  transition: transform 0.3s ease;
}
.swiper-item {
  flex: 0 0 100%;
  height: 100%;
}
.swiper-item img {
  width: 100%;
  height: auto;
  object-fit: cover;
  border-radius: 8px;
}
.swiper-dots {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
}
.dot {
  width: 8px;
  height: 8px;
  background: #b0bec5;
  border-radius: 50%;
  cursor: pointer;
}
.dot.active {
  background: #4fc3f7;
}
.basic {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.basic-icon img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  cursor: pointer;
}
.basic-info {
  flex: 1;
}
.basic-info .name {
  font-size: 16px;
  font-weight: bold;
  color: #e0e0e0;
}
.basic-info .time {
  font-size: 12px;
  color: #b0bec5;
}
.follow-btn-container {
  width: 20%;
}
.logout-btn {
  padding: 8px 16px;
  background: #4fc3f7;
  color: #fff;
  border-radius: 5px;
  text-align: center;
  cursor: pointer;
}
.logout-btn:hover {
  background: #29b6f6;
}
.news-text {
  font-size: 16px;
  color: #e0e0e0;
  line-height: 1.8;
  margin-bottom: 20px;
}
.news-divider {
  border-top: 1px solid #f1f1f1;
  margin: 20px 0;
}
</style>
